package com.lanyuan.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    public static final Integer STATUS_OK = 200;

    public static final Integer STATUS_ERROR = 401;

    public static final Map<Integer, String> DEFAULT_MESSAGE_FOR_STATUS = new HashMap<>();

    private Integer code;

    private String msg;

    private Map<String, Object> data;

    static {
        DEFAULT_MESSAGE_FOR_STATUS.put(STATUS_OK, "成功");
        DEFAULT_MESSAGE_FOR_STATUS.put(STATUS_ERROR, "失败");
    }

    private Result(Integer code, String msg) {
        this(code, msg, null);
    }

    public void initData() {
        if (data == null) {
            data = new LinkedHashMap<>();
        }
    }

    public Result add(String key, Object value) {
        initData();
        data.put(key, value);
        return this;
    }

    public static Result ok(String msg) {
        return new Result(STATUS_OK, StringUtils.isEmpty(msg) ? DEFAULT_MESSAGE_FOR_STATUS.get(STATUS_OK) : msg);
    }

    public static Result ok() {
        return ok(null);
    }

    public static Result error(String msg) {
        return new Result(401, msg);
    }

    public static Result error(Integer code, String msg) {
        return new Result(code, msg);
    }

}
